/*!
 * Querystring module v1.0.0 of jRaiser javascript library
 * http://code.google.com/p/jraiser/
 *
 * Author: Heero.Luo
 * Licensed under MIT license
 *
 * Date: Tue Feb 14 2012 11:05:28 GMT+0800
 */
define(function(require, exports, module) { 'use strict';

var core = require('core/1.0.x/core');


function stringify(data, o) {
	o = core.mix({
		encode : encodeURIComponent
	}, o);

	var result = [ ];
	core.each(data, function(val, key) {
		result.push( o.encode(key) + '=' + o.encode(val) );
	});

	return result.join('&');
}

core.extend(exports, {
	/**
	 * 把数据转换为URL参数
	 * @param {Object} 数据字典
	 * @param {Object} 设置
	 *   encode {Function} 编码函数，默认为encodeURIComponent
	 * @return {String} URL参数
	 */
	stringify : stringify,
	
	/**
	 * 把URL参数转换为数据
	 * @param {String} URL参数，默认为当前URL的参数
	 * @param {Object} 设置
	 *   decode {Function} 解码函数，默认为decodeURIComponent
	 * @return {Object} 数据字典
	 */
	parse : function (qs, o) {
		o = core.mix({
			decode : decodeURIComponent
		}, o);
		
		var data = { }, i = 0;

		qs = ( qs || window.location.search.substr(1) ).split(/[&=]/);

		while (i < qs.length) {
			data[o.decode(qs[i++])] = o.decode(qs[i++]);
		}

		return data;
	},
	
	/**
	 * 把数据以GET参数形式添加到URL
	 * @param {String} URL
	 * @param {Object,String} 数据
	 * @return {String} 处理后的URL
	 */
	append : function(url, data) {
		if (!data) { return url; }
		
		if (typeof data !== 'string') {
			data = stringify(data);
		}
		data = data.replace(/^[?&]+/, '');
		
		var temp = url.indexOf('#'), hash = '';
		if (temp !== -1) {
			hash = url.substring(temp, url.length);
			url = url.substring(0, temp);
		}
		url = url.replace(/[?&]+$/, '');
		
		return url + (url.indexOf('?') === -1 ? '?' : '&') + data + hash;
	}
});

});